<template>
	<el-dialog :title="titleMap[mode]" v-model="visible" width="70%" destroy-on-close @closed="$emit('closed')" align-center :close-on-click-modal="false">
		<el-form :model="form" :rules="rules" :disabled="mode == 'show'" ref="dialogForm" label-width="110px" label-position="right">
            <el-row :gutter="1">
                <el-col :span="8">
                    <el-form-item label="项目编号" prop="project_code">
                        <el-input v-model="project_code" readonly placeholder="请选择项目" @click="checkItem"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="会议名称" prop="referrer_name">
                        <el-input v-model="referrer_name" readonly></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="会议时间" prop="referrer_time">
                        <el-input v-model="referrer_time" readonly></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="1">
                <el-col :span="8">
                    <el-form-item label="报价金额合计" prop="offer_total">
                        <el-input v-model="form.offer_total" readonly></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="商品成本合计" prop="cost_total">
                        <el-input v-model="form.cost_total" readonly></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="创建时间" prop="date">
                        <el-date-picker v-model="date" type="date" placeholder="请选择创建时间" style="width: 100%;" :value-format="'YYYY-MM-DD'" disabled></el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="1">
                <el-col :span="8">
                    <el-form-item label="附件" prop="offer_files">
                        <sc-upload-file v-model="form.offer_files">
                            <el-button type="primary" size="small">上传文件</el-button>
                        </sc-upload-file>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="备注" prop="remark">
                        <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" clearable></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-form-item label="报价商品清单" prop="offer_detail">
                <el-button type="primary" size="small" icon="el-icon-plus" @click="checkProduct">选择商品</el-button>
                <sc-form-table ref="table" class="formtable" v-model="form.offer_detail" :addTemplate="product" placeholder="暂无数据" height="350" hideAdd show-summary @tableDel="totalCompute">
                    <el-table-column label="商品名称" align="center">
                        <template #default="scope">
                            <div>{{ scope.row.goods_name }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column label="分类名称" align="center">
                        <template #default="scope">
                            <el-cascader v-model="scope.row.goods_cate_id" :options="cateList" :props="cateProps" :show-all-levels="false" clearable style="width: 100%;"></el-cascader>
                            <!-- <div>{{ scope.row.cate_name }}</div> -->
                        </template>
                    </el-table-column>
                    <el-table-column label="单位" align="center">
                        <template #default="scope">
                            <div>{{ scope.row.unit }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column label="明细" align="center">
                        <template #default="scope">
                            <el-input v-model="scope.row.detail" placeholder="明细" @focus="onFocus($event)"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="成本价" prop="price_cost" align="center">
                        <template #default="scope">
                            <div>{{ scope.row.price_cost }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column label="商品报价" prop="goods_offer_price" align="center">
                        <template #default="scope">
                            <el-input v-model="scope.row.goods_offer_price" placeholder="商品报价" @focus="onFocus($event)" @input="totalCompute"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="数量" prop="num" align="center">
                        <template #default="scope">
                            <el-input v-model="scope.row.num" placeholder="数量" @focus="onFocus($event)" @input="totalCompute"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="金额" prop="fee" align="center">
                        <template #default="scope">
                            <el-input v-model="scope.row.fee" placeholder="小计" readonly></el-input>
                        </template>
                    </el-table-column>
                </sc-form-table>
            </el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="visible = false">取 消</el-button>
			<el-button v-if="mode != 'show'" type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
		</template>
	</el-dialog>
    <item-list v-if="dialog.item" ref="itemDialog" @success="itemBack" @closed="dialog.item=false"></item-list>
    <product-list v-if="dialog.product" ref="productDialog" @success="productBack" @closed="dialog.product=false"></product-list>
</template>

<script>
import ProductList from '@/views/product/info/productList.vue';
import itemList from '../list/itemList.vue';
export default {
    components: { itemList, ProductList },
	emits: ['success', 'closed'],
	data() {
		return {
			mode: "add",
			titleMap: {
				add: '新增报价单',
				edit: '编辑报价单',
				show: '查看'
			},
			visible: false,
			isSaveing: false,
            dialog:{
                item:false,
                product:false,
            },
			//表单数据
			form: {
                id:"",
				offer_code: "",
                project_id:"",
                offer_total:"",
                cost_total:"",
                offer_files:"",
                remark:"",
                offer_detail:[],
			},
            date:this.moment().format('YYYY-MM-DD'),
            project_code:"",
            referrer_name:"",
            referrer_time:"",
            product:{},
            cateList: [],
            cateProps: {
                value: "id",
                emitPath: false,
                checkStrictly: true
            },
            is_project:false,
		}
	},
	mounted() {
        this.getCate()
	},
	methods: {
		//显示
		open(mode = 'add') {
			this.mode = mode;
			this.visible = true;
			return this
		},
		//表单提交方法
		submit() {
			this.$refs.dialogForm.validate(async (valid) => {
				if (valid) {
					this.isSaveing = true;
					var res = [];
					if (this.form.id) {
						res = await this.$API.project.offer.edit.post(this.form);
					} else {
						res = await this.$API.project.offer.add.post(this.form);
					}
					this.isSaveing = false;
					if (res.code == 1) {
						this.$emit('success', this.form, this.mode)
						this.visible = false;
						this.$message.success("操作成功")
					} else {
						this.$alert(res.message, "提示", { type: 'error' })
					}
				} else {
					return false;
				}
			})
		},
        projectData(data){
            this.is_project = true
            this.form.project_id = data.project_id
            this.project_code = data.project_code
            this.referrer_name = data.referrer_name
            this.referrer_time = data.referrer_time
        },
		//表单注入数据
		async setData(data) {
            this.form.id = data.id
            var res = await this.$API.project.offer.detail.get({id:data.id});
            this.form.offer_code = res.data.offer_code
            this.form.project_id = data.project_id
            this.form.offer_total = data.offer_total
            this.form.cost_total = data.cost_total
            this.form.remark = data.remark
            this.form.offer_files = data.offer_files
            let array = []
            res.data.offer_detail.map(item=>{
                array.push({
                    id:item.id,
                    goods_id:item.goods_id,
                    goods_name:item.goods.goods_name,
                    goods_cate_id:item.goods_cate_id,
                    unit:item.goods.unit,
                    cate_name:item.cate_name,
                    detail:item.detail,
                    goods_offer_price:item.goods_offer_price,
                    price_cost:item.goods.purchase_price,
                    num:item.num,
                    fee:Number(item.goods_offer_price) * item.num
                })
            })
            this.form.offer_detail = array
            this.project_code = data.project.project_code
            this.referrer_name = data.project.metting
            this.referrer_time = data.project.project_time
            this.date = data.create_time
		},
        onFocus(event){
            event.target.select();
        },
        //获取商品分类
        async getCate(){
            var res = await this.$API.product.cate.list.get();
            this.cateList = res.data;
        },
        checkItem(){
            if(!this.is_client){
                this.dialog.item = true
                this.$nextTick(() => {
                    this.$refs.itemDialog.open('add')
			    })
            }
        },
        itemBack(data){
            this.form.offer_code = data.project_code
            this.form.project_id = data.id
            this.project_code = data.project_code
            this.referrer_name = data.metting
            this.referrer_time = data.project_time
        },
        checkProduct(){
            this.dialog.product = true
			this.$nextTick(() => {
				this.$refs.productDialog.open('add')
			})
        },
        productBack(data){
            let array = []
            data.map((item)=>{
                array.push({
                    goods_id:item.id,
                    goods_name:item.goods_name,
                    goods_cate_id:item.cate_id,
                    unit:item.unit,
                    cate_name:item.cate_name,
                    detail:"",
                    goods_offer_price:item.purchase_price,
                    price_cost:item.purchase_price,
                    num:1,
                })
            })
            let existingIds = this.form.offer_detail.map(item => item.goods_id);
            for(let i = array.length - 1; i >= 0; i--){
                if(existingIds.includes(array[i].goods_id)){
                    array.splice(i, 1);
                }
            }
            this.form.offer_detail = [...this.form.offer_detail,...array]
            this.totalCompute()
            // let count_price = 0
            // let count_prices = 0
            // this.form.offer_detail.map(item => {
            //     if(item.num && item.goods_offer_price){
            //         item.fee = (Number(item.num) * Number(item.goods_offer_price)).toFixed(2)
            //         count_price = (Number(count_price) + Number(item.fee)).toFixed(2)
            //         count_prices = Number(count_prices) + Number(item.price_cost)
            //     }
            // })
            // this.form.offer_total = count_price 
            // this.form.cost_total = count_prices
        },
        totalCompute(){
            let count_price = 0
            let count_prices = 0
            this.form.offer_detail.map(item => {
                if(item.num && item.goods_offer_price){
                    item.fee = (Number(item.num) * Number(item.goods_offer_price)).toFixed(2)
                    count_price = (Number(count_price) + Number(item.fee)).toFixed(2)
                    count_prices = Number(count_prices) + (Number(item.price_cost) * Number(item.num))
                }
            })
            this.form.offer_total = count_price 
            this.form.cost_total = count_prices
        },
	}
}
</script>

<style></style>
